// static/js/school_mgmt.js
;(function(){
  // —— 模块作用域内状态 ——
  let schools = [];
  let editingId = null;
  let adding = false;

  // —— DOM 引用 ——
  const msgEl  = document.getElementById('schoolMgmtMsg');
  const tbody  = document.getElementById('school-tbody');
  const addBtn = document.getElementById('add-school-btn');

  // —— 弹窗打开时初始化 ——
  document.getElementById('schoolMgmtModal')
    .addEventListener('show.bs.modal', async () => {
      msgEl.style.display = 'none';
      adding    = false;
      editingId = null;
      addBtn.disabled = false;
      await loadSchools();
    });

  // —— 从后端加载学校列表 ——
  async function loadSchools() {
    try {
      const res = await fetch('/api/schools');
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      schools = await res.json();
      renderSchools();
    } catch (e) {
      showMsg('加载失败：' + e.message);
    }
  }

  // —— 绑定失焦校验 ——
  function bindBlur(el, validateFn) {
    el.addEventListener('blur', () => {
      const v = el.value.trim();
      if (!validateFn(v)) {
        el.classList.add('input-invalid');
        el.addEventListener('animationend', () => {
          el.classList.remove('input-invalid');
        }, { once: true });
      }
    });
  }

  // —— 渲染表格 ——
  function renderSchools() {
    tbody.innerHTML = '';

    // 普通行
    schools.forEach(s => {
      if (editingId === s.id) return;
      const disabled = (adding || editingId !== null) ? 'disabled' : '';
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td class="align-middle text-center">
          <span class="school-name" data-bs-toggle="tooltip" title="${s.name}">
            ${s.name}
          </span>
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-secondary me-1" ${disabled}
                  onclick="moveSchool(${s.id}, 'up')" title="上移">
            <i class="bi bi-arrow-up"></i>
          </button>
          <button class="btn btn-sm btn-outline-secondary me-1" ${disabled}
                  onclick="moveSchool(${s.id}, 'down')" title="下移">
            <i class="bi bi-arrow-down"></i>
          </button>
          <button class="btn btn-sm btn-outline-info me-1" ${disabled}
                  onclick="enterEditSchool(${s.id})" title="编辑">
            <i class="bi bi-pencil-fill"></i>
          </button>
          <button class="btn btn-sm btn-outline-danger" ${disabled}
                  onclick="deleteSchool(${s.id})" title="删除">
            <i class="bi bi-trash-fill"></i>
          </button>
        </td>`;
      tbody.appendChild(tr);
    });

    // 新增行
    if (adding) {
      const trNew = document.createElement('tr');
      trNew.id = 'new-school-row';
      trNew.innerHTML = `
        <td class="align-middle text-center">
          <input type="text" id="new-school-input"
                 class="form-control form-control-sm text-center" value="">
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-success me-1"
                  onclick="saveNewSchool()"
                  title="保存">
            <i class="bi bi-check-lg"></i>
          </button>
          <button class="btn btn-sm btn-outline-secondary"
                  onclick="cancelNewSchool()"
                  title="取消">
            <i class="bi bi-x-lg"></i>
          </button>
        </td>`;
      tbody.appendChild(trNew);

      const inp = document.getElementById('new-school-input');
      inp.focus();
      bindBlur(inp, v => v !== '' && !schools.some(x => x.name === v));
    }

    // 编辑行
    if (editingId !== null) {
      const s = schools.find(x => x.id === editingId);
      const trEdit = document.createElement('tr');
      trEdit.id = 'edit-school-row';
      trEdit.innerHTML = `
        <td class="align-middle text-center">
          <input type="text" id="edit-school-input"
                 class="form-control form-control-sm text-center"
                 value="${s.name}">
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-success me-1"
                  onclick="saveEditSchool(${s.id})"
                  title="保存">
            <i class="bi bi-check-lg"></i>
          </button>
          <button class="btn btn-sm btn-outline-secondary"
                  onclick="cancelEditSchool()"
                  title="取消">
            <i class="bi bi-x-lg"></i>
          </button>
        </td>`;
      // 插入到正确位置
      const idx = schools.findIndex(x => x.id === editingId);
      const rows = Array.from(tbody.children);
      if (rows.length === 0 || idx >= rows.length) {
        tbody.appendChild(trEdit);
      } else {
        tbody.insertBefore(trEdit, rows[idx]);
      }

      const inp = document.getElementById('edit-school-input');
      inp.focus();
      bindBlur(inp, v => v !== '' && !schools.some(x => x.name === v && x.id !== editingId));
    }

    // 初始化所有 Tooltip
    const tipElems = tbody.querySelectorAll('[data-bs-toggle="tooltip"]');
    tipElems.forEach(el => new bootstrap.Tooltip(el));
  }

  // —— 进入新增模式 ——
  addBtn.addEventListener('click', () => {
    if (adding || editingId !== null) return;
    adding = true;
    addBtn.disabled = true;
    renderSchools();
  });

  // —— 取消新增 ——
  window.cancelNewSchool = function() {
    adding = false;
    addBtn.disabled = false;
    renderSchools();
  };

  // —— 保存新增 ——
  window.saveNewSchool = async function() {
    const input = document.getElementById('new-school-input');
    const name = input.value.trim();
    if (!name) return showMsg('学校名不能为空');
    if (schools.some(x => x.name === name)) return showMsg('学校名已存在');
    try {
      const res = await fetch('/api/schools', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name })
      });
      const text = await res.text();
      const payload = JSON.parse(text);
      if (!res.ok) throw new Error(payload.error || payload.message || text);
      adding = false;
      addBtn.disabled = false;
      await loadSchools();
    } catch (e) {
      showMsg(e.message);
    }
  };

  // —— 进入编辑模式 ——
  window.enterEditSchool = function(id) {
    if (adding || editingId !== null) return;
    editingId = id;
    addBtn.disabled = true;
    renderSchools();
  };

  // —— 取消编辑 ——
  window.cancelEditSchool = function() {
    editingId = null;
    addBtn.disabled = false;
    renderSchools();
  };

  // —— 保存编辑 ——
  window.saveEditSchool = async function(id) {
    const input = document.getElementById('edit-school-input');
    const name = input.value.trim();
    if (!name) return showMsg('学校名不能为空');
    if (schools.some(x => x.name === name && x.id !== id)) return showMsg('学校名已存在');
    try {
      const res = await fetch(`/api/schools/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name })
      });
      const text = await res.text();
      const payload = JSON.parse(text);
      if (!res.ok) throw new Error(payload.error || payload.message || text);
      editingId = null;
      addBtn.disabled = false;
      await loadSchools();
    } catch (e) {
      showMsg(e.message);
    }
  };

  // —— 删除 ——
  window.deleteSchool = async function(id) {
    try {
      const res = await fetch(`/api/schools/${id}`, { method: 'DELETE' });
      const text = await res.text();
      const payload = JSON.parse(text);
      if (!res.ok) throw new Error(payload.error || payload.message || text);
      await loadSchools();
    } catch (e) {
      showMsg('删除失败：' + e.message);
    }
  };

  // —— 上移/下移 ——
  window.moveSchool = async function(id, dir) {
    try {
      await fetch(`/api/schools/${id}/move`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dir })
      });
      await loadSchools();
    } catch (e) {
      showMsg('移动失败：' + e.message);
    }
  };

  // —— 通用消息提示 ——
  function showMsg(msg) {
    msgEl.textContent = msg;
    msgEl.style.display = 'inline';
    setTimeout(() => { msgEl.style.display = 'none'; }, 3000);
  }
})();
